<script setup>
    import {
        Edit,
        Delete,
        BellFilled,
        Search
    } from '@element-plus/icons-vue'
    import {onMounted, ref} from 'vue'
    // 导入 ExcelJS 库
    import ExcelJS from 'exceljs/dist/exceljs.min.js';
    //声明一个异步的函数
    import {
        CourseAddService,
        CourseUpdateService,
        CourseDeleteService,
        CourseListBySearchService
    } from '@/api/course.js'
    import {
        ProfessionListAllSerivce
    } from '@/api/profession.js'
    import {
        TeacherListAllSerivce,
        fetchTeachersByProfession
    } from '@/api/teacher.js'
    import {
        ElMessage,
        ElMessageBox
    } from 'element-plus'
    const courses = ref([{
        "courseId":1,
        "courseName":"",
        "courseSemester":"",
        "courseCreditHour":"",
        "teacherId":"",
        "professionId":""
    }])
    //分页
    const currentPage = ref(1)
    const pageSize = ref(5)
    const total = ref(20)
    const handleSizeChange = (val) => {
        pageSize.value = val;
        search();
    }
    const handleCurrentChange = (val) => {
        currentPage.value = val;
        search();
    }
    const professions = ref([{
        "professionId":1,
        "professionName":"",
        "professionType":""
    }])
    const professionAll = async () => {
        try {
            const result = await ProfessionListAllSerivce();
            professions.value = result.data;
        } catch (error) {
            ElMessage({
                type: 'error',
                message: '搜索出错',
            });
        }
    }
    const teachers = ref([{
        "teacherId":1,
        "teacherName":"",
        "teacherPhone":"",
        "teacherPhoto":"",
        "professionId":""
    }])
    const teacherAll = async () => {
        try {
            const result = await TeacherListAllSerivce();
            teachers.value = result.data;
        } catch (error) {
            ElMessage({
                type: 'error',
                message: '搜索出错',
            });
        }
    }

    onMounted(() => {
        professionAll();
        teacherAll();
        search();
    });
    //控制添加弹窗
    const dialogVisible = ref(false)

    //添加数据模型
    const courseModel = ref({
        courseName:'',
        courseSemester:'',
        courseCreditHour:'',
        teacherId:null,
        professionId:null
    })
    const id = ref({
        courseId: ''
    })
    //添加表单校验
    const rules = {
        title:[{
            required: true,
            message: '请输入标题',
            trigger: 'blur'
        },],
        content: [{
            required: true,
            message: '请输入内容',
            trigger: 'blur'
        }, ],
        startTime: [{
            required: true,
            message: '请输入开始时间',
            trigger: 'blur'
        }, ],
        endTime: [{
            required: true,
            message: '请输入结束时间',
            trigger: 'blur'
        }, ]
    }

    //调用接口添加数据
    const addCourse = async () => {
        let result = await CourseAddService(courseModel.value);
        if(result.code===1){
            ElMessage.success('添加成功')
        }else{
            ElMessage.error(result.msg)
        }
        search();
        dialogVisible.value = false;
    }

    //定义变量，控制标题的展示
    const title = ref('')
    //展示编辑弹窗
    const showDialog = (row) => {
        dialogVisible.value = true;
        title.value = '编辑课程';
        // 数据拷贝
        courseModel.value.courseName = row.courseName;
        courseModel.value.courseSemester = row.courseSemester;
        courseModel.value.courseCreditHour = row.courseCreditHour;
        courseModel.value.teacherId = row.teacherId;
        courseModel.value.professionId = row.professionId;
        // 扩展ID属性，需要传输给后台
        courseModel.value.courseId = row.courseId;
    }

    //编辑
    const updateCourse = async () => {
        //调用接口
        let result = await CourseUpdateService(courseModel.value);
        if(result.code===1){
            ElMessage.success('修改成功')
        }else {
            ElMessage.error(result.msg);
        }
        search();
        dialogVisible.value = false;
    }
    //清空模型的数据
    const clearData = () => {
        courseModel.value.courseName = '';
        courseModel.value.courseSemester = '';
        courseModel.value.courseCreditHour = '';
        courseModel.value.teacherId = '';
        courseModel.value.professionId = '';
    }
    //删除
    const deleteCourse = async (row) => {
        //提示用户
        ElMessageBox.confirm(
                '你即将要删除该信息，确认吗?',
                '温馨提示', {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            )
            .then(async () => {
                //调用接口
                await CourseDeleteService(row.courseId);
                search();
                ElMessage({
                    type: 'success',
                    message: '删除成功',
                });

            })
            .catch(() => {
                ElMessage({
                    type: 'info',
                    message: '已取消',
                })
            })
    }


    const multipleSelection = ref([])
    const deleteSelected = () => {
        if (multipleSelection.value.length === 0) {
            ElMessage({
                type: 'error',
                message: '并不存在数据',
            });
            return;
        }
        performDelete();
    }
    //异步删除方法
    const performDelete = async () => {
        try {
            for (const selectedItem of multipleSelection.value) {
                await CourseDeleteService(selectedItem.courseId);
            }
            search();
            ElMessage({
                type: 'success',
                message: '批量删除成功',
            });
        } catch (error) {
            ElMessage({
                type: 'error',
                message: '删除选定项目时出错',
            });
        }
    }
    const handleSelectionChange = (val) => {
        multipleSelection.value = val
    }
    // 导出
    const exportSelected = () => {
        if (multipleSelection.value.length === 0) {
            ElMessage({
                type: 'error',
                message: '请选择要导出的数据',
            });
            return;
        }

        // 创建一个新的工作簿
        const workbook = new ExcelJS.Workbook();

        // 添加一个工作表
        const worksheet = workbook.addWorksheet('Sheet1');

        // 设置表头信息
        worksheet.addRow(['课程名称','开设学期','课程学分','负责老师','所属专业']);

        // 获取选择的数据
        const selectedData = multipleSelection.value;

        // 将数据添加到工作表中
        selectedData.forEach(row => {
            worksheet.addRow([
                row.courseName,
                row.courseSemester,
                row.courseCreditHour,
                row.teacherName,
                row.professionName
            ]);
        });

        // 将工作簿保存为Excel文件
        workbook.xlsx.writeBuffer()
            .then(buffer => {
                const blob = new Blob([buffer], {
                    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
                });
                const fileName = '课程数据.xlsx';

                // 创建下载链接并触发下载
                const link = document.createElement('a');
                link.href = URL.createObjectURL(blob);
                link.download = fileName;
                link.click();

                ElMessage({
                    type: 'success',
                    message: '导出成功',
                });
            })
            .catch(error => {
                console.error('导出Excel文件时出错:', error);
                ElMessage({
                    type: 'error',
                    message: '导出失败',
                });
            });
    }
      //搜索
    const input = ref("");
    const select = ref("1");
    const search = async () => {
        try {
            const result = await CourseListBySearchService(input.value, select.value, currentPage.value, pageSize.value);
            console.log(result);
            courses.value = result.data.rows;
            total.value = result.data.total;
            // 遍历专业数据，获取对应的专业名称并添加到班级对象中
            courses.value.forEach(course => {
                const profession = professions.value.find(prof => prof.professionId === course.professionId);
                if (profession) {
                    course.professionName = profession.professionName;
                }
            });
            // 遍历教师数据，获取对应的教师名称并添加到班级对象中
            courses.value.forEach(course => {
                const teacher = teachers.value.find(teac => teac.teacherId === course.teacherId);
                if (teacher) {
                course.teacherName = teacher.teacherName;
                }
            });
        } catch (error) {
            ElMessage({
                type: 'error',
                message: '搜索出错',
            });
        }
    }

    const tempTeachers =ref([{
        "teacherId":1,
        "teacherName":"",
        "teacherPhone":"",
        "teacherPhoto":"",
        "professionId":""
    }])
    // 监听所选专业变化，获取对应的老师列表
    const handleProfessionChange = async () => {
        try {
            const selectedProfessionId = courseModel.value.professionId;
            const result = await fetchTeachersByProfession(selectedProfessionId);
            tempTeachers.value = result.data;
        } catch (error) {
            ElMessage({
                type: 'error',
                message: '获取老师列表出错',
            });
        }
    }
</script>
<template>
    <div class="card-container">
        <el-card class="page-container">
            <template #header>
                <div class="header">
                    <span style="font-size: 14px;"><b>课程管理</b></span>
                    <div class="extra">
                        <el-input v-model="input" placeholder="请输入" class="input-with-select">
                            <template #prepend>
                                <el-select v-model="select" placeholder="课程名称" style="width: 115px">
                                    <el-option label="课程名称" value="1" />
                                    <el-option label="负责老师" value="3" />
                                    <el-option label="所属专业" value="2" />
                                </el-select>
                            </template>
                            <template #append>
                                <el-button :icon="Search" @click="search(input,select,currentPage,pageSize)" />
                            </template>
                        </el-input>
                        <el-button type="success" @click="exportSelected()" plain>导出</el-button>
                        <el-button type="danger" @click="deleteSelected()">批量删除</el-button>
                        <el-button type="primary" @click="dialogVisible=true;title='添加课程';clearData()">添加课程</el-button>
                    </div>
                </div>
            </template>
            <el-table :data="courses" style="width: 100%" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column label="序号" width="150" type="index"> </el-table-column>
                <el-table-column label="课程名称" width="200" prop="courseName"></el-table-column>
                <el-table-column label="开设学期" width="200" prop="courseSemester"></el-table-column>
                <el-table-column label="课程学分" width="140" prop="courseCreditHour"></el-table-column>
                <el-table-column label="负责老师" width="200" prop="teacherName"></el-table-column>
                <el-table-column label="所属专业" width="150" prop="professionName"></el-table-column>
                <el-table-column label="操作" width="150">
                    <template #default="{ row }">
                        <el-button :icon="Edit" circle plain type="primary" @click="showDialog(row)"></el-button>
                        <el-button :icon="Delete" circle plain type="danger" @click="deleteCourse(row)"></el-button>
                    </template>
                </el-table-column>
                <template #empty>
                    <el-empty description="没有数据" />
                </template>
            </el-table>

            <el-dialog v-model="dialogVisible" :title="title" width="50%" >
                <el-form :model="courseModel" :rules="rules" label-width="100px" style="padding-right: 30px">
                    <el-form-item label="课程名称" prop="courseName">
                        <el-input v-model="courseModel.courseName" minlength="1"></el-input>
                    </el-form-item>
                    <el-form-item label="开设学期" prop="courseSemester">
                        <el-input v-model="courseModel.courseSemester" minlength="1"></el-input>
                    </el-form-item>
                    <el-form-item label="课程学分" prop="courseCreditHour">
                        <el-input v-model="courseModel.courseCreditHour" minlength="1"></el-input>
                    </el-form-item>
                    <el-form-item label="所属专业" prop="professionId">
                        <el-select v-model="courseModel.professionId" placeholder="请选择所属专业" @change="handleProfessionChange">
                            <el-option
                            v-for="profession in professions"
                            :key="profession.professionId"
                            :label="profession.professionName"
                            :value="profession.professionId">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="负责老师" prop="teacherId">
                        <el-select v-model="courseModel.teacherId" placeholder="请选择负责老师">
                            <el-option
                            v-for="teacher in tempTeachers"
                            :key="teacher.teacherId"
                            :label="teacher.teacherName"
                            :value="teacher.teacherId">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="dialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="title=='添加课程'?addCourse():updateCourse()"> 确认 </el-button>
                    </span>
                </template>
            </el-dialog>
        </el-card>
    </div>
    <el-pagination class="el-p" v-model:current-page="currentPage" v-model:page-size="pageSize"
        :page-sizes="[5, 10, 15, 20]" :background="true" layout="jumper,total, sizes, prev, pager, next " :total="total"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
</template>

<style lang="scss" scoped>
    .card-container {
        height: 520px;
        /* 设置合适的固定高度 */
        overflow: auto;
    }

    .page-container {
        min-height: 100%;
        box-sizing: border-box;

        .header {
            display: flex;
            align-items: center;
            justify-content: space-between;

            .extra {
                display: flex;
                align-items: center;

                .el-input {
                    margin-right: 400px;
                }
            }
        }
    }

    .custom-date-picker {
        display: flex;
        width: 100%;
        padding: 0;
        flex-wrap: wrap;
    }

    .el-p {
        margin-top: 20px;
        display: flex;
        justify-content: flex-end;
    }

    .input-with-select {
        background-color: var(--el-fill-color-blank);
    }
    // 调整样式
:deep(.ql-editor) {
  min-height: 180px;
}
:deep(.ql-formats) {
  height: 21px;
  line-height: 21px;
}

</style>